package com.linran.poll.service.loop;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.concurrent.Callable;

@Slf4j
public class LoopPullTask implements Callable<String> {
    @Setter
    @Getter
    private volatile String data;
    private Long TIME_OUT_MILLIS = 10000L;

    /*方式一：这种方式如果没有数据变更的情况下，cpu资源被白白浪费掉;在高并发情况下所有线程都在竞争cpu资源,while(true)不仅浪费宝贵的cpu资源，而且还容易使cpu崩溃*/

    @Override
    public String call() throws Exception {
        long startTime = System.currentTimeMillis();
        while (true) {
            if (!StringUtils.isEmpty(data)) {
                return data;
            }
            if (isTimeOut(startTime)) {
                log.info("[pull超时] ~~~~~");
                data = "请求超时";
                return data;
            }
            Thread.sleep(200);
        }
    }

    private boolean isTimeOut(long startTime) {
        long nowTime = System.currentTimeMillis();
        return nowTime - startTime > TIME_OUT_MILLIS;
    }


}
